import { createStore } from 'vuex'
import auth from './modules/auth'
import pets from './modules/pets'
import adoptions from './modules/adoptions'
import categories from './modules/categories'

export default createStore({
  state: {
    loading: false,
    error: null
  },
  mutations: {
    SET_LOADING(state, status) {
      state.loading = status
    },
    SET_ERROR(state, error) {
      state.error = error
      // Log errors to help with debugging
      if (error) {
        console.error('Application Error:', error)
      }
    },
    CLEAR_ERROR(state) {
      state.error = null
    }
  },
  actions: {
    setLoading({ commit }, status) {
      commit('SET_LOADING', status)
    },
    setError({ commit }, error) {
      // Skip certain expected errors
      if (error && typeof error === 'string' && error.includes('加载分类数据失败')) {
        console.warn('忽略错误:', error);
        return;
      }
      
      // Format error object if necessary
      let errorMessage = error;
      if (error && typeof error === 'object') {
        if (error.message) {
          errorMessage = error.message;
        } else if (error.response && error.response.data && error.response.data.message) {
          errorMessage = error.response.data.message;
        } else {
          errorMessage = JSON.stringify(error);
        }
      }
      
      commit('SET_ERROR', errorMessage)
    },
    clearError({ commit }) {
      commit('CLEAR_ERROR')
    }
  },
  getters: {
    isLoading: state => state.loading,
    error: state => state.error
  },
  modules: {
    auth,
    pets,
    adoptions,
    categories
  }
}) 